package sf.ext.gen;

import sf.database.dbinfo.TableInfo;
import sf.tools.StringUtils;

import java.util.HashMap;
import java.util.Map;

public class MapperImplCodeGen implements CodeGen {
    /**
     *
     */
    String pkg = null;
    private String mapperImplTemplate = "";
    /**
     * 映射接口路径
     */
    private String mapperPkg;

    public MapperImplCodeGen() {
        mapperImplTemplate = GenUtils.getTemplate("/template/gen/mapperimpl.enjoy");
    }

    public MapperImplCodeGen(String pkg) {
        this();
        this.pkg = pkg;
    }

    public String getMapperImplTemplate() {
        return mapperImplTemplate;
    }

    public void setMapperImplTemplate(String mapperImplTemplate) {
        this.mapperImplTemplate = mapperImplTemplate;
    }

    public String getMapperPkg() {
        return mapperPkg;
    }

    public void setMapperPkg(String mapperPkg) {
        this.mapperPkg = mapperPkg;
    }

    @Override
    public void genCode(String srcPath, String entityPkg, String entityClass, TableInfo tableDesc, GenConfig config, boolean isDisplay) {
        if (pkg == null) {
            pkg = entityPkg;
        }
        if (srcPath == null) {
            srcPath = GenUtils.getJavaSRCPath();
        }
        Map<String, Object> map = new HashMap<>();
        String mapperInfClass = entityClass + "DAO";
        String className = entityClass + "DAOImpl";
        map.put("className", className);
        map.put("mapperInfClass", mapperInfClass);
        map.put("package", pkg);
        map.put("entityClass", entityClass);

        StringBuilder mapperHead = new StringBuilder();
        mapperHead.append("import ").append(entityPkg).append(".*;").append(PojoGen.CR);
        if (StringUtils.isNotBlank(mapperPkg)) {
            mapperHead.append("import ").append(mapperPkg).append(".*;").append(PojoGen.CR);
        }
        map.put("imports", mapperHead.toString());
        String mapperCode = GenUtils.renderByEnjoy(map, mapperImplTemplate);
        if (isDisplay) {
            System.out.println(mapperCode);
        } else {
            try {
                GenUtils.saveSourceFile(srcPath, pkg, className, mapperCode);
            } catch (Exception e) {
                throw new RuntimeException("mapper代码生成失败", e);
            }
        }

    }

}
